const Db = require("../utils/db");
const modules = {};

/**
 * 记录圣诞树日志
 */
modules.readRecord = (ip) => {
  return new Promise((resolve, reject) => {
    const sql = `SELECT * FROM christmas_tree where ip="${ip}" LIMIT 0, 1000`;
    Db(sql, (err, res) => {
      if (err) {
        reject(err.sqlMessage || err);
      }
      if (res) {
        resolve(res);
      }
    });
  });
};
modules.record = (form) => {
  return new Promise((resolve, reject) => {
    const sql = `INSERT INTO christmas_tree set?`;
    Db(sql, form, (err, res) => {
      if (err) {
        reject(err.sqlMessage || err);
      }
      if (res) {
        resolve(res);
      }
    });
  });
};
modules.updateRecord = (form) => {
  return new Promise((resolve, reject) => {
    const sql = `UPDATE christmas_tree SET time='${form.time}' WHERE (id='${form.id}')`;
    Db(sql, form, (err, res) => {
      if (err) {
        reject(err.sqlMessage || err);
      }
      if (res) {
        resolve(res);
      }
    });
  });
};

/**
 * 记录水电
 */
modules.add = (form) => {
  return new Promise((resolve, reject) => {
    const sql = `INSERT INTO record set?`;
    Db(sql, form, (err, res) => {
      if (err) {
        reject(err.sqlMessage || err);
      }
      if (res) {
        resolve(res);
      }
    });
  });
};

/**
 * 获取记录
 */
modules.list = (uid, query) => {
  return new Promise((resolve, reject) => {
    let sql = `SELECT * FROM record WHERE u_id = "${uid}"`;
    if (query.startDate) {
      sql += ` AND insert_date >= "${query.startDate}"`;
    }
    if (query.endDate) {
      sql += ` AND insert_date <= "${query.endDate}"`;
    }
    sql += ` ORDER BY insert_date DESC`;
    Db(sql, (err, res) => {
      if (err) {
        reject(err.sqlMessage || err);
      }
      if (res) {
        resolve(res.map((item) => {
          return {
            id: item.id,
            uId: item.u_id,
            recordType: item.record_type,
            insertType: item.insert_type,
            amount: item.amount,
            balance: item.balance,
            insertDate: item.insert_date,
            createDate: item.create_date,
          }
        }));
      }
    });
  });
};


module.exports = modules;
